package com.fdb.basic.framework.core.util;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
 * 
 * Java序列化
 * 
 * @author Cytus_
 * @since 2018年5月7日 下午7:55:22
 * @version 1.0
 *
 */
public final class SerializeUtils {
	
	
	public static String SERIALIZE_CHARSET = "UTF-8";

	
	/**
	 * 序列化
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public static <T> String serializeStr(T object) throws Exception {
		return new String(Base64.encodeBase64(serialize(object)), SERIALIZE_CHARSET);
	}
    
	
	/**
	 * 序列化
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        if (obj == null) {
            throw new RuntimeException("序列化对象(" + obj + ")!");
        }
        Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
        } finally {
            buffer.clear();
        }
        return protostuff;
    }

	
	/**
	 * 反序列化
	 * @param str
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
    public static <T> T deserialize(String str, Class<T> clazz) throws Exception {  
      	byte[] bytes = Base64.decodeBase64(str.getBytes(SERIALIZE_CHARSET));
         return deserialize(bytes, clazz);
	}
    
    
    /**
     * 反序列化
     * @param paramArrayOfByte
     * @param targetClass
     * @return
     */
    public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }
        T instance = null;
        try {
            instance = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e);
        }
        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
        return instance;
    }
    
    
    /**
     * 序列化LIST对象
     * @param objList
     * @return
     * @throws Exception
     */
    public static <T> String serializeListStr(List<T> objList) throws Exception {
    	return new String(Base64.encodeBase64(serializeList(objList)), SERIALIZE_CHARSET);
    }
    
    
    /**
     * 序列化LIST对象
     * @param objList
     * @return
     */
    public static <T> byte[] serializeList(List<T> objList) {
        if (objList == null || objList.isEmpty()) {
            throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
        }
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(objList.get(0).getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
            protostuff = bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
        } finally {
            buffer.clear();
            try {
                if(bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
            }
        }
        
        return protostuff;
    }
    
    
    /**
     * 反序列化LIST对象
     * @param str
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> List<T> deserializeList(String str, Class<T> clazz) throws Exception {
    	byte[] bytes = Base64.decodeBase64(str.getBytes(SERIALIZE_CHARSET));
        return deserializeList(bytes, clazz);
    }
    
    
    /**
     * 反序列化LIST对象
     * @param paramArrayOfByte
     * @param targetClass
     * @return
     */
    public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }
        
        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        List<T> result = null;
        try {
            result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
        } catch (IOException e) {
            throw new RuntimeException("反序列化对象列表发生异常!",e);
        }
        return result;
    }
	
}
